package com.nageoffer.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nageoffer.shortlink.admin.common.constant.RedisCacheConstant;
import com.nageoffer.shortlink.admin.common.convention.abstractException.ClientException;
import com.nageoffer.shortlink.admin.common.enums.UserErrorCodeEnum;
import com.nageoffer.shortlink.admin.dao.entity.UserDO;
import com.nageoffer.shortlink.admin.dao.mapper.UserMapper;
import com.nageoffer.shortlink.admin.dto.req.UserLoginReqDTO;
import com.nageoffer.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.nageoffer.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.nageoffer.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.nageoffer.shortlink.admin.dto.resp.UserRespDTO;
import com.nageoffer.shortlink.admin.service.GroupService;
import com.nageoffer.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
//TODO 为什么要继承ServiceImpl

/**
 * 用户接口实现层
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {
    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final GroupService groupService;

    /**
     * 根据用户名查询用户
     *
     * @param username 用户名
     */
    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username);
        //可以调用原生的baseMapper里的方法查询
        //UserDO userDO = baseMapper.selectOne(queryWrapper);
        UserDO userDO = getOne(queryWrapper);
        if (BeanUtil.isEmpty(userDO)) {
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        return BeanUtil.copyProperties(userDO, UserRespDTO.class);
    }

    /**
     * 查询用户名是否存在
     *
     * @param username 用户名
     */
    @Override
    public Boolean hasUsername(String username) {
        /*LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username);
        UserDO userDO = getOne(queryWrapper);*/
        return userRegisterCachePenetrationBloomFilter.contains(username);
    }

    /**
     * 用户注册
     *
     * @param userRegisterReqDTO 注册用户请求参数
     */
    @Override
    public void register(UserRegisterReqDTO userRegisterReqDTO) {
        //1.检验用户名是否存在
        if (Boolean.TRUE.equals(hasUsername(userRegisterReqDTO.getUsername()))) {
            throw new ClientException(UserErrorCodeEnum.USER_NAME_EXIST);
        }

        //2.添加分布式锁
        RLock lock = redissonClient.getLock(RedisCacheConstant.LOCK_USER_REGISTER_KEY + userRegisterReqDTO.getUsername());
        //2.1 获取不到锁直接返回
        if (!lock.tryLock()) {
            throw new ClientException(UserErrorCodeEnum.USER_NAME_EXIST);
        } else {
            //2.2 获取到锁后
            //添加失败，提示用户存在
            if (!save(BeanUtil.toBean(userRegisterReqDTO, UserDO.class))) {
                throw new ClientException(UserErrorCodeEnum.USER_SAVE_EXIST);
            }

            //往布隆过滤器里添加用户名
            userRegisterCachePenetrationBloomFilter.add(userRegisterReqDTO.getUsername());
            groupService.saveGroup(userRegisterReqDTO.getUsername(), "默认分组");
            lock.unlock();
        }


    }

    /**
     * 根据用户名修改用户
     *
     * @param userUpdateReqDTO
     */
    @Override
    public void update(UserUpdateReqDTO userUpdateReqDTO) {
        //TODO 验证当前用户是否为登录用户
        //LambdaUpdateWrapper<UserDO> wrapper = new LambdaUpdateWrapper<UserDO>().eq(UserDO::getUsername, userUpdateReqDTO.getUsername());
        //update(BeanUtil.toBean(userUpdateReqDTO,UserDO.class),wrapper);
        //lambdaUpdate().setEntity(BeanUtil.toBean(userUpdateReqDTO,UserDO.class)).eq(UserDO::getUsername, userUpdateReqDTO.getUsername()).update();
        lambdaUpdate()
                .eq(UserDO::getUsername, userUpdateReqDTO.getUsername())
                .update(BeanUtil.toBean(userUpdateReqDTO, UserDO.class));
    }

    /**
     * 用户登录
     *
     * @param userLoginReqDTO 用户登录请求参数
     */
    @Override
    public UserLoginRespDTO login(UserLoginReqDTO userLoginReqDTO) {
        LambdaQueryWrapper<UserDO> lambdaQueryWrapper = new LambdaQueryWrapper<>(UserDO.class)
                .eq(UserDO::getUsername, userLoginReqDTO.getUsername())
                .eq(UserDO::getPassword, userLoginReqDTO.getPassword());
        UserDO userDO = getOne(lambdaQueryWrapper);
        if (BeanUtil.isEmpty(userDO)) {
            throw new ClientException("用户不存在");
        }
        Boolean hasLogin = stringRedisTemplate.hasKey("login_" + userLoginReqDTO.getUsername());
        if (hasLogin != null && hasLogin) {
            throw new ClientException("用户已登录");
        }
        String uuid = UUID.randomUUID().toString();
        // 添加：键，值，30，秒
        /**
         * Hash
         * Key:login_用户名
         * Value:
         *  Key:token 标识
         *  Val:JSON 字符串（用户信息）
         */
        // TODO 这不会导致同个用户30天只能登录一次吗
        stringRedisTemplate.opsForHash().put("login_" + userLoginReqDTO.getUsername(), uuid, JSON.toJSONString(userDO));
        stringRedisTemplate.expire(userLoginReqDTO.getUsername(), 30L, TimeUnit.DAYS);
        return new UserLoginRespDTO(uuid);
    }

    /**
     * 检查用户是否登录
     *
     * @param username
     * @param token    用户登录Token
     * @return 用户是否登录标识
     */
    @Override
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get("login_" + username, token) != null;
    }

    /**
     * 用户登出
     *
     * @param username
     * @param token
     */
    @Override
    public void logout(String username, String token) {
        if (checkLogin(username, token)) {
            stringRedisTemplate.delete("login_" + username);
            return;
        }
        throw new ClientException("用户Token不存在或用户未登录");
    }
}
